<script>

import { Plus, Edit, Check, Close } from '@element-plus/icons'

export default {
  data: function () {
    return {
      'tasks': []
    }
  },
  methods: {
    edit: function (index) {
      var currentItem = this.tasks[index];
      currentItem.edit = true;
    },
    finish: function (index) {
      var currentItem = this.tasks[index];
      currentItem.edit = false;
      window.localStorage.setItem('data-todo-list-tasks', JSON.stringify(this.tasks));
    },
    create: function () {
      this.tasks.push({edit: true, value:''})
    },
    remove: function (index) {
      this.tasks.splice(index, 1);
      window.localStorage.setItem('data-todo-list-tasks', JSON.stringify(this.tasks));
    }
  },
  mounted: function () {
    var data = window.localStorage.getItem('data-todo-list-tasks');
    try {
      this.tasks = JSON.parse(data);
      this.tasks = this.tasks && this.tasks.length ? this.tasks : []; 
    } catch (e) {
      this.tasks = [];
    }
  },
  components: {
    Plus,
    Edit,
    Check,
    Close 
  }
}
</script>

<template>
  <h1>Todo List</h1>
  <el-row v-for="(item, index) in tasks" class="align-left">
    <el-col :span="12" :offset="4" class="border-bottom">
      <span v-if="!item.edit" @click="edit(index)" >{{item.value}}</span>
      <el-input v-else v-model="item.value" @blur="finish(index)" placeholder="new task here ..." />
    </el-col>
    <el-col :span="2" class="border-bottom">
      <el-button v-if="!item.edit" @click="edit(index)" type="primary">
        <el-icon class="align-middle"><edit /></el-icon>
        &nbsp;&nbsp;Edit Item
      </el-button>
      <el-button v-else @click="finish(index)" type="success">
        <el-icon class="align-middle"><check /></el-icon>
        &nbsp;&nbsp;Save Item
      </el-button>
    </el-col>
    <el-col :span="2" class="border-bottom">
    <el-button @click="remove(index)" type="danger">
        <el-icon class="align-middle"><close /></el-icon>
        &nbsp;&nbsp;Remove Item
      </el-button>
    </el-col>
  </el-row>
  <el-row class="align-left">
    <el-col :span="16" :offset="4" style="padding: 10px;">
      <el-button @click="create" type="primary">
        <el-icon class="align-middle"><plus /></el-icon>
        &nbsp;&nbsp;New Item
      </el-button>
    </el-col>
  </el-row>
</template>

<style scoped>
  .main {
    font-size: 40px;
    font-weight: bold;
    height: 80px;
    line-height: 80px;
    background-color: #AAAAAA;
    margin-bottom: 40px;
  }
  .border-bottom {
    padding: 10px;
    line-height: 42px;
    border-bottom: solid 1px #AAAAAA;
  }
  .align-left {
    text-align: left;
  }
  .align-middle {
    vertical-align: middle;
  }
</style>
